package cn.itcast.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    public static void main(String[] args) throws Exception{
        //1.创建线程组
        EventLoopGroup group = new NioEventLoopGroup();

        //2.创建客户端的启动助手完成相关配置
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group) //设置线程组
                .channel( NioSocketChannel.class) //设置客户端的通道的实现类
                .handler(new ChannelInitializer<SocketChannel>() { //创建通道初始化对象
                    public void initChannel(SocketChannel socketChannel){
                        socketChannel.pipeline().addLast(new NettyClientHandler()) ;//往pin中添加自定义handler
                    }
                });
        System.out.println("客户端已准备就绪....");
        //3.启动客户端连接服务器端(异步非阻塞)
        ChannelFuture cf = bootstrap.connect("127.0.0.1", 9999).sync();

        //4.关闭连接(非阻塞)
        cf.channel().closeFuture().sync();

    }
}
